package cn.tedu.sp11.fallback;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ItemFallback implements FallbackProvider {
    /**
     * 返回一个服务id，表示当前这个降级类，是针对哪个服务的降级类
     * @return
     */
    @Override
    public String getRoute() {
        //当执行item-service失败，
        //应用当前这个降级类
        return "item-service";
        //星号和null都表示所有微服务失败都应用当前降级类
        //return "*"或者null;
    }

    /**
     * 向客户端发回的降级响应，封装到response对象
     * @param route
     * @param cause
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {

        return new ClientHttpResponse() {
            //下面三个方法都是协议号
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {
                //关闭流，关闭inputStream
            }

            @Override
            public InputStream getBody() throws IOException {
                String json = JsonResult.err().msg("调用商品服务失败").toString();

                return new ByteArrayInputStream(json.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                //设置协议头可以携带字符
                HttpHeaders h=new HttpHeaders();
                h.setContentType(MediaType.APPLICATION_JSON);
                return h;
            }
        };
    }
}
